<?php
/**
 * 功能方法类库集合文件
 */

//**** 引入外部类库文件 ****//

require LIB_PATH . 'contents.php';   // 网络访问方法

//**** 内部定义方法 ****//

/**
 * 判断环境类型编码输出
 * @param  [type] $Str [description]
 * @return [type]      [description]
 */
function print_f($Str, $sleep = null)
{
    if (php_sapi_name() == 'cli') {
        if (stripos(php_uname('s'), 'windows') !== false) {
            echo iconv('utf-8', 'gb2312', $Str);
        } else {
            echo $Str;
        }
        is_numeric($sleep) && sleep($sleep);
    } else {
        echo $Str;
    }
    if (is_bool($sleep) && $sleep == true) exit;
}

/**
 * 获取文章库文章
 * @param  [type] $mark [description]
 * @param  [type] $num  [description]
 * @return [type]       [description]
 */
function getDalArticle($mark, $num = 1)
{
    $url = "http://dal.120open.com/Home/Api/article/?mark={$mark}&num={$num}&callback=(";
    $ret = Get_Web_Contents($url);
    if ($ret['Info']['http_code'] != 200) return false;

    $articleList = json_decode(trim($ret['Body'], '();'), true);
    if (!$articleList) return false;

    return $articleList;
}

/**
 * 替换文章内的关键词
 * @param  [type] $body    [description]
 * @param  [type] $hosType [description]
 * @param  [type] $title   [description]
 * @return [type]          [description]
 */
function postBodyReplace($body, $hosType, $title, $imgFile)
{
    global $hosRepKey;

    // 删除多于换行
    $body = str_ireplace(array("\r", "\n", '  '), '', $body);

    // 循环 替换 医院标记  循环每一个 标记
    foreach ($hosRepKey[$hosType] as $tagName => $tagValue) {
        if (is_array($tagValue)) $tagValue = $tagValue[array_rand($tagValue)];
        $tagValue = trim($tagValue);
        $body = str_ireplace('{$' . $tagName . '}', $tagValue, $body);
    }

    // 把 技术标记 删除
    $body = str_ireplace('{$HospitalSkill}', '', $body);

    // 替换商务通标记
    $body = preg_replace('#{$HospitalSwt}#', '<a href="javascript:;" target="_self" onclick="BsSwt.Class.OpenSwt(\'\',\'2\');return false;" rel="nofollow">立即在线咨询</a>', $body);
    $body = preg_replace('#{$HospitalSwt\.([^}]+)}#', '<a href="javascript:;" target="_self" onclick="BsSwt.Class.OpenSwt(\'\',\'2\');return false;" rel="nofollow">$1</a>', $body);

    // 替换关键词标记
    $body = str_ireplace('{$PostKeyword}', $title, $body);

    // 强制加首行空格
    $body = str_ireplace('<p', '<p style="text-indent: 2em;"', $body);

    // 插入图片 40% 的 几率插入
    if (rand(1, 100) <= 40) {
        // 获取图片
        $imgStr = file_get_contents($imgFile);
        $imgArr = explode("\n", $imgStr);
        $imgNum = array_rand($imgArr, 1);
        $imgUrl = $imgArr[$imgNum];
        $body = preg_replace('#<\/[pP]>\s*<[pP]#', "</p><p style=\"text-align: center;\"><img src=\"{$imgUrl}\" alt=\"{$title}\" title=\"{$title}\" /></p><p", $body, 1);
    }

    // // 插入商务通
    // $swtID = rand(0, 113);
    // $swtUrl = "/static/article/swt/{$swtID}.gif";
    // $body.= "<p style=\"text-align: center;\"><a href=\"javascript:;\" target=\"_self\" onclick=\"BsSwt.Common.OpenSwt('','2');return false;\" rel=\"nofollow\"><img alt=\"立即咨询\" title=\"立即咨询\" src=\"{$swtUrl}\" /></a></p>";

    $body = preg_replace('#<img[^>]+>#i', '<center>$0</center>', $body);

    return $body;
}

// csv转json
function csv2json($csvFileName, $headContr = array(), $isBody = false)
{
    // 获取 CSV内容
    $csvBody = $isBody ? $csvFileName : file_get_contents($csvFileName);

    // 读取并转换编码
    $csvCharset = mb_detect_encoding($csvBody, array('ASCII', 'UTF-8', 'GB18030', 'GB2312', 'GBK'));

    // 判断并转换编码
    if ($csvCharset != 'UTF-8') {
        $csvBody = mb_convert_encoding($csvBody, 'UTF-8', $csvCharset);
    }

    // 处理Csv内容
    $csvArr = explode("\n", $csvBody);
    $jsonArr = array();
    // 循环每一行记录
    foreach ($csvArr as $id => $value) {
        // 第一行为表头
        if ($id == 0) {
            $csvTabList = explode(',', trim($value));

            foreach ($csvTabList as $csvTabId => $csvTabName) {
                // 对应表头拼音
                foreach ($headContr as $headKey => $headValue) {
                    if (trim($csvTabName) == trim($headValue)) {
                        $csvTabList[$csvTabId] = trim($headKey);
                    }
                }
            }
        } else {
            // 空行跳过
            if (empty(trim($value))) continue;
            // 解析单条记录字段
            $arrTmp = explode(',', $value);
            $arrInfo = array();
            // 循环每个字段对应的表头
            foreach ($arrTmp as $aid => $val) {
                $arrInfo[$csvTabList[$aid]] = trim($val);
            }
            $jsonArr[] = $arrInfo;
        }
    }
    return $jsonArr;
}

/**
 * 获取关键词
 * @param  [type] $fileName [description]
 * @param  [type] $num      [description]
 * @return [type]           [description]
 */
function getFileKeyword($fileName)
{
    // 获取日志文件名
    $fileLogName = preg_replace('#\.([a-z0-9A-Z]+)$#', '_info.$1', $fileName);#文件名获取到日志
    $fileLogStr = file_exists($fileLogName) ? file_get_contents($fileLogName) : "x\n0";
    $fileLog = explode("\n", $fileLogStr);

    // 判断关键词文件是否修改
    $keyFileHash = md5_file($fileName); #文件名的md5值
    $fileLogId = $keyFileHash == trim($fileLog['0']) ? intval($fileLog['1']) : 0;

    // 读取关键词文件
    $keyFileStr = file_get_contents($fileName);

    // 读取并转换编码
    $fileCharset = mb_detect_encoding($keyFileStr, array('ASCII', 'UTF-8', 'GB18030', 'GB2312', 'GBK'));

    // 判断并转换编码
    if ($fileCharset != 'UTF-8')
        $keyFileStr = mb_convert_encoding($keyFileStr, 'UTF-8', $fileCharset);

    //\r \r\n 都统一替换成 \n
    $keyFileStr = preg_replace("#(\r\n|\r|\n\n)#", "\n", $keyFileStr);

    // 分解关键词列表
    $keyList = explode("\n", $keyFileStr);

    //过滤关键词列表
    /*
     *因需求更改，故注释此段代码
    if ($keyFileHash != trim($fileLog['0'])){
        $singleKeyList = array();//初始化
        $keyFileName = preg_replace("#.+?([a-z]+)_[a-z]+\.txt#",'$1',$fileName);
        $keyFile = POST_KEY_LOG.$keyFileName."_key.csv";
        $publishKeyStr = file_get_contents($keyFile);//读取已发布的关键词文件
        $publishKeyList = explode("\n",$publishKeyStr);

        //已发布的关键词————过滤日期标识，去除空元素，去重复
        foreach($publishKeyList as $k => $v){
            $match = preg_match("#\d{4}(-\d{2}){2} \d{2}(:\d{2}){2}#",$v);
            if ($match !== 0 || empty($v)) continue;
            $temp = explode(",",$v);
            $singleKeyList = array_filter(array_unique(array_merge($temp,$singleKeyList)));
        }

        //关键词列表————去重复
        foreach($keyList as $k2 => $v2){
            if (in_array(trim($v2),$singleKeyList)) unset($keyList[$k2]);
        }
        $new_keyFileStr = implode("\n",$keyList);
        file_put_contents($fileName,$new_keyFileStr);//过滤并更新关键词列表
    }*/

//    echo $fileLogId;

    $fileLogId = empty($keyList[$fileLogId + 1]) ? 0 : $fileLogId;

    // 获取一个关键词
    $keyword = trim($keyList[$fileLogId++]);

    // 保存本次的ID
    file_put_contents($fileLogName, "{$keyFileHash}\n{$fileLogId}");

    //避免空行
    if (empty($keyword)) {
        $keyword = getFileKeyword($fileName);
    }

    return $keyword;
}

//更新关键词（ID）标示
function modityKeyId($fileName)
{
    // 获取日志文件名
    $fileLogName = preg_replace('#\.([a-z0-9A-Z]+)$#', '_info.$1', $fileName);
    $fileLogStr = file_exists($fileLogName) ? file_get_contents($fileLogName) : "x\n0";
    $fileLog = explode("\n", $fileLogStr);
    //获取ID
    $fileLogId = intval($fileLog['1']);
    if ($fileLogId >= 1) $fileLogId--;

    // 修改本次的ID
    file_put_contents($fileLogName, "{$fileLog[0]}\n{$fileLogId}");
}

/**
 * 获取随机图片
 * @param  [type] $fileName [description]
 * @param  [type] $num      [description]
 * @return [type]           [description]
 */
function getRandImg($fileName)
{
    // 文件不存在则返回
    if (!file_exists($fileName))
        return '1';

    // 读取关键词文件
    $keyFileStr = file_get_contents($fileName);

    // 读取并转换编码
    $fileCharset = mb_detect_encoding($keyFileStr, array('ASCII', 'UTF-8', 'GB18030', 'GB2312', 'GBK'));

    // 判断并转换编码
    if ($fileCharset != 'UTF-8')
        $keyFileStr = mb_convert_encoding($keyFileStr, 'UTF-8', $fileCharset);

    // 分解关键词列表
    $keyList = explode("\n", $keyFileStr);

    // 数量为空也返回\
    if (count($keyList) <= 0) return '2';

    // 获取一个关键词
    $i = rand(0, count($keyList) - 1);
    return basename(trim($keyList[$i]));
}

function baidu_push($url, $i = 0)
{
    // 提交地址
    $pushUrl = 'http://api.share.baidu.com/s.gif?l=' . $url;

    // 追加协议头
    $header = array(
        'Referer' => $url,
        'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.101 Safari/537.36'
    );

    // 提交到百度
    $retHtml = Get_Web_Contents($pushUrl, 'GET', '', '', $header);

    if (empty($retHtml["Info"]["http_code"])) {
        return false;
    }

    if ($retHtml["Info"]["http_code"] == 200) {
        return true;
    }

    if ($retHtml["Info"]["http_code"] == 302) {
        return false;
    }
}

//执行百度推送计划
function do_baiduPush($all_list, $userName, $day, $date)
{
    $pushFail = array();//初始化
    $pustNum = count($all_list);
    print_f("\n[百度推送] 账号：{$userName} 主动推送 {$day}（{$date}） {$pustNum} 条链接...\n");
    $pust_i = 0;
    foreach ($all_list as $postUrl) {
        $ret = baidu_push($postUrl);
        $pust_i += $ret ? 1 : 0;
        if ($ret) {
            print_f("\t{$postUrl}\t[OK]\n", 1);
        } else {
            print_f("\t{$postUrl}\t[NO]\n", 1);
            $pushFail[] = $postUrl;
        }
        sleep(1);
    }
    $push_e = $pustNum - $pust_i;
    print_f("成功 {$pust_i} 条 , 失败 {$push_e} 条\n");

    if (!empty($pushFail)) {
        print_r("\n休息30s后，推送失败的链接将再次推送\n");
        sleep(30);
        do_baiduPush($pushFail, $userName, $day, $date);
    } else {
        print_r("[百度推送] 账号：{$userName} 主动推送 {$day}（{$date}） 所有链接推送完毕...\n");
        return true;
    }
}


//获取指定日期，已发布文章的所有链接
function getPostUrlList($userName, $date)
{
    $retList = $all_list = array();//初始化
    $contents = file_get_contents(POST_URL_KEY_LIST . $userName . ".csv"); //得到保存在keylist里面的名字对应的信息

    #匹配出昨天的文章
    $contents = preg_replace("#{$date} \d{2}(:\d{2}){2}(\n|\r\n|\r)#", "[breakpoint]", $contents); //将空格替换成 [breakpoint]
    $arr_contents = explode("[breakpoint]", $contents);

    //获取指定日期的文章链接
    $target_str = empty($arr_contents[1]) ? "" : $arr_contents[1];

    if (!empty($target_str)) {
        $arr_url = explode("\n", $target_str);
        foreach ($arr_url as $v) {
            $arr_urlList = explode(",", $v);

            if (!empty($arr_urlList[0]) && !empty($arr_urlList[1]) && !empty($arr_urlList[2])) {
                $retList['info'][] = $arr_urlList[0];
                $retList['wap'][] = $arr_urlList[1];
                $retList['title'][] = $arr_urlList[2];
            }
        }

        $all_list = array_filter(array_merge($retList['info'], $retList['wap'], $retList['title']));
    } else {
        $all_list = false;
    }
    return $all_list;
}

/**
 *
 * @param array $userList 用户信息，主要取用户名
 * @param string $day  日期：今天/昨天
 */

function pushBaidu($userList, $day)
{
    $time = time();
    foreach ($userList as $userName => $userInfo) {
        if ($day == '昨天') {
            if (time() - $time > 60 * 60) { //昨天的连接，推送超过 1小时就停止
                break;
            }
            $date = date("Y-m-d", strtotime("-1 day"));
        } elseif ($day == '今天') {
            $date = date("Y-m-d");
        }
        // 获取最近4页的所有连接 并推送到百度
        $all_list = getPostUrlList($userName, $date);
        if (!$all_list) {
            print_r("获取{$day}的文章链接【失败】!!!\n");
            continue;
        }
        // 执行百度推送
        $ret = do_baiduPush($all_list, $userName, $day, $date);
        if ($ret) continue;
    }
}
